<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="小组名称" prop="groupName">
        <el-input
          v-model="queryParams.groupName"
          placeholder="请输入小组名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卓越班" prop="classID">
        <el-select v-model="queryParams.classID" placeholder="请选择卓越班班级"
                   style="width: 220px" clearable @keyup.enter="handleQuery">
          <el-option v-for="item in classinfoList" :key="item.className" :label="item.className" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--        >导出-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="groupsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="小组名称" align="center" prop="groupName" />
      <el-table-column label="卓越班班级" align="center" prop="classID">
        <template #default="scope">
          <span>{{ getClassInfo(scope.row.classID) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="小组组长" align="center" prop="groupLeaderID">
        <template #default="scope">
          <span>{{CheekLeader(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最大成员数" align="center" prop="maxMembers" />
      <el-table-column label="创建时间" align="center" prop="createdDate" width="180">
        <template #default="scope">
          <span>{{ scope.row.createdDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Right" @click="handleView(scope.row)"></el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 30, 40]"
      @size-change="getList"
      @current-change="getList"
      class="custom-pagination"
    />

    <!-- 添加或修改小组对话框 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-form ref="groupsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="小组名" prop="groupName">
          <el-input v-model="form.groupName" placeholder="请输入小组名" style="width: 220px" />
        </el-form-item>
        <el-form-item label="卓越班" prop="classID">
          <el-select v-model="form.classID" placeholder="请选择卓越班班级"
                     style="width: 220px" clearable @keyup.enter="handleQuery">
            <el-option v-for="item in classinfoList" :key="item.className" :label="item.className" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="最大成员" prop="maxMembers">
          <el-input type="number" v-model="form.maxMembers" placeholder="请输入最大成员数" style="width: 220px" />
        </el-form-item>
        <el-form-item label="小组长" prop="groupLeaderID">
          <el-select v-model="form.groupLeaderID" placeholder="请选择小组长" style="width: 220px" clearable>
            <el-option v-for="item in GroupMembersListByGroup"
                       :key="item.studentID"
                       :label="item.stuName+item.studentID"
                       :value="item.studentID"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Groups" lang="ts">
import { addGroups, delGroups, getGroups, listGroups, updateGroups } from '@/apis/system/groups'
import { getCurrentInstance, reactive, ref, toRefs, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listClassinfo } from '@/apis/system/classinfo'
import { GroupStore } from '@/stores/group'
import router from '@/router'
import { listGroupMembers } from '@/apis/system/groupMembers'

const { proxy } = getCurrentInstance() as { proxy: any }
const groupStore = GroupStore()
const groupsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')

const data = reactive({
  form: {
    groupID: null,
    groupName: null,
    classID: null,
    maxMembers: null,
    groupLeaderID: null,
    createdDate: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    groupName: null,
    classID: null,
    groupLeaderID: null,
    createdDate: null
  },
  rules: {
    groupName: [
      { required: true, message: '小组名不能为空', trigger: 'blur' }
    ],
    classID: [
      { required: true, message: '卓越班班级不能为空', trigger: 'blur' }
    ],
    maxMembers: [
      { required: true, message: '最大成员数不能为空', trigger: 'blur' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

const classinfoList = ref<any[]>([])
const ClassinfoqueryParams = ref({
  pageNum: 1,
  pageSize: 100000000
})
// 获取卓越班班级
listClassinfo(ClassinfoqueryParams.value).then(response => {
  if (response.data.code === 200) {
    classinfoList.value = response.data.data.records
    total.value = response.data.data.total
  } else {
    ElMessage({
      message: response.data.msg,
      type: 'error'
    })
  }
})

const GroupMembersList = ref<any[]>([])
const GroupMembersListByGroup = ref<any[]>([])

const GroupMembersQueryParams = ref({
  pageNum: 1,
  pageSize: 100000000,
  groupID: null
})

// 查询小组成员
listGroupMembers(GroupMembersQueryParams.value).then(response => {
  if (response.data.code === 200) {
    GroupMembersList.value = response.data.data.records
    GroupMembersListByGroup.value = response.data.data.records
  } else {
    ElMessage({
      message: response.data.msg,
      type: 'error'
    })
  }
})

//回显当前学号的姓名加学号
function CheekLeader(row:any){
  for(let i=0;i<GroupMembersList.value.length;i++){
    if(row.groupLeaderID===GroupMembersList.value[i].studentID){
      return GroupMembersList.value[i].stuName +GroupMembersList.value[i].studentID
    }
  }
}

// 回显当前小组的班级
function getClassInfo(classID: number | string): string {
  const classInfo = classinfoList.value.find(item => item.id === classID)
  return classInfo ? classInfo.className : '未知班级'
}

/** 查询小组列表 */
function getList() {
  loading.value = true
  listGroups(queryParams.value).then(response => {
    if (response.data.code === 200) {
      groupsList.value = response.data.data.records
      total.value = response.data.data.total
    } else {
      ElMessage({
        message: response.data.msg,
        type: 'error'
      })
    }
    loading.value = false
  })
}
// 取消按钮
function cancel() {
  open.value = false
  GroupMembersListByGroup.value=GroupMembersList.value
  reset()
}

// 表单重置
function reset() {
  form.value = {
    groupID: null,
    groupName: null,
    classID: null,
    maxMembers: null,
    groupLeaderID: null,
    createdDate: null
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    groupName: null,
    classID: null,
    groupLeaderID: null,
    createdDate: null
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection: any[]) {
  ids.value = selection.map(item => item.groupID)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加小组'
  GroupMembersListByGroup.value= [];
}

/** 修改按钮操作 */
function handleUpdate(row: any) {
  reset()
  GroupMembersListByGroup.value=GroupMembersList.value.filter((item:any)=>{
    if(row.groupID==null)return true;
    return row.groupID===item.groupID
  })
  const _groupID = row.groupID || ids.value
  getGroups(_groupID).then(response => {
    form.value = response.data.data
    open.value = true
    title.value = '修改小组'
  })
}

// 查看按钮操作
function handleView(row: any) {
  groupStore.groupInfo.groupID = row.groupID
  groupStore.groupInfo.OriginGroupPath = router.currentRoute.value.path
  groupStore.groupInfo.classID = row.classID
  groupStore.groupInfo.groupLeaderID = row.groupLeaderID
  router.push({ path: '/Group/GroupsMembers' })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['groupsRef'].validate((valid: boolean) => {
    if (valid) {
      if (form.value.groupID != null) {
        updateGroups(form.value).then(response => {
          if (response.data.code === 200) {
            ElMessage({ type: 'success', message: '更新成功' })
            getList()
          } else {
            ElMessage({ type: 'error', message: response.data.msg })
          }
          open.value = false

        })
      } else {
        addGroups(form.value).then(response => {
          if (response.data.code === 200) {
            ElMessage({ type: 'success', message: '新增成功' })
            getList()
          } else {
            ElMessage({ type: 'error', message: response.data.msg })
          }
          open.value = false
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row: any) {
  const _groupIDs = row.groupID || ids.value
  ElMessageBox.alert('是否确认删除？', '提示', {
    confirmButtonText: '确定',
    callback: (action: string) => {
      if (action === 'confirm') {
        delGroups(_groupIDs).then(response => {
          if (response.data.code === 200) {
            ElMessage({ type: 'success', message: '删除成功' })
            getList()
          }else {
            ElMessage({ type: 'error', message: response.data.msg })
          }
        })
      }
    }
  })
}

// /** 导出按钮操作 */
// function handleExport() {
//   proxy.download('system/groups/export', {
//     ...queryParams.value
//   }, `groups_${new Date().getTime()}.xlsx`)
// }

getList()
</script>

<style scoped lang="scss">
.custom-pagination {
  margin-top: 20px; /* 调整分页组件与表格的间距 */
  display: flex;
  justify-content: center; /* 居中对齐分页组件 */
}

.custom-pagination .el-pagination__total,
.custom-pagination .el-pagination__sizes,
.custom-pagination .el-pager li,
.custom-pagination .btn-prev,
.custom-pagination .btn-next,
.custom-pagination .el-pagination__jump {
  font-size: 14px; /* 调整字体大小 */
  color: #333; /* 调整文字颜色 */
}

.custom-pagination .el-pagination__sizes .el-input .el-input__inner {
  height: 30px; /* 调整输入框高度 */
  line-height: 30px; /* 调整输入框行高 */
}

.custom-pagination .el-pager li {
  min-width: 30px; /* 调整分页按钮最小宽度 */
  height: 30px; /* 调整分页按钮高度 */
  line-height: 30px; /* 调整分页按钮行高 */
  background-color: #f5f7fa; /* 调整分页按钮背景颜色 */
  border-radius: 4px; /* 调整分页按钮圆角 */
  margin: 0 5px; /* 调整分页按钮间距 */
}

.custom-pagination .el-pager li.active {
  background-color: #409eff; /* 调整激活分页按钮背景颜色 */
  color: #fff; /* 调整激活分页按钮文字颜色 */
}

.custom-pagination .btn-prev,
.custom-pagination .btn-next {
  height: 30px; /* 调整前后按钮高度 */
  line-height: 30px; /* 调整前后按钮行高 */
  background-color: #f5f7fa; /* 调整前后按钮背景颜色 */
  border-radius: 4px; /* 调整前后按钮圆角 */
  margin: 0 5px; /* 调整前后按钮间距 */
}

.custom-pagination .btn-prev:hover,
.custom-pagination .btn-next:hover {
  background-color: #409eff; /* 调整前后按钮悬停背景颜色 */
  color: #fff; /* 调整前后按钮悬停文字颜色 */
}
</style>
